<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";

const animationDuration = 6000;
var that;
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "400px",
    },
    BXdata: {
      type: Array,
      default: () => [],
    },
    BSdata: {
      type: Array,
      default: () => [],
    },
    BSname: "",
    BStitle: {
      type: Array,
      default: () => [],
    },
    rend: false,
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart(true);
    });
    that = this;
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  watch: {
    rend() {
      this.initChart();
    },
  },
  methods: {
    initChart(flag) {
      this.chart = echarts.init(this.$el, "macarons");

      this.chart.setOption({
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
          formatter(params) {
            for (let i = 0; i < params.length; i++) {
              if (params[i].seriesName != "") {
                var returnData =
                  (that.BStitle.length > 0
                    ? `名称：${that.BStitle[params[i].dataIndex]}<br/>`
                    : "" + `标题：${params[i].name}<br/>`) +
                  `${params[i].seriesName}：${params[i].value}`;
              }
            }
            return returnData;
          },
        },
        grid: {
          top: 10,
          left: "2%",
          right: "2%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: this.BXdata,
            axisLabel: { interval: 0, rotate: 30 },
          },
        ],
        yAxis: [
          {
            type: "value",
            axisTick: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: this.BSname,
            title: this.BStitle,
            type: "bar",
            stack: "vistors",
            barWidth: "60%",
            label: {
              show: true,
              position: "inside",
            },
            data: this.BSdata,
            animationDuration,
          },
        ],
      });
      if (flag) {
        this.chart.on("click", function handleClick(params) {
          that.$emit("handleSelectDoc", params.dataIndex);
        });
      }
    },
  },
};
</script>
